<?php

namespace AppBundle;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\Validator\Validation;
use Symfony\Bridge\Twig\Form\TwigRendererEngine;
use Symfony\Component\Form\Forms;
use Symfony\Component\Form\Extension\Validator\ValidatorExtension;
use Symfony\Component\Form\Extension\Csrf\CsrfExtension;
use Symfony\Component\Security\Csrf\CsrfTokenManager;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\Loader\XliffFileLoader;
use Symfony\Bridge\Twig\Extension\TranslationExtension;
use Symfony\Bridge\Twig\Extension\FormExtension;
use Symfony\Bridge\Twig\Form\TwigRenderer;

class AppBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        define('BASE_DIR',realpath(__DIR__.'/../..'));
        define('VENDOR_DIR', BASE_DIR.'/vendor');
        define('SYMFONY_DIR',VENDOR_DIR.'/symfony/symfony/src/Symfony');
        define('VENDOR_FORM_DIR', SYMFONY_DIR . '/Component/Form');
        define('VENDOR_VALIDATOR_DIR', SYMFONY_DIR . '/Component/Validator');
        define('VENDOR_TWIG_BRIDGE_DIR', SYMFONY_DIR . '/Bridge/Twig');
        define('VIEWS_DIR', realpath(BASE_DIR.'/app/Resources/views'));
        define('TRANSLATIONS_DIR',realpath(BASE_DIR.'/app/Resources/translations'));
        $csrfTokenManager = new CsrfTokenManager();
        $validator = Validation::createValidator();
        $translator = new Translator('zh_CN');
        $translator->addLoader('xlf', new XliffFileLoader());
        $translator->addResource('xlf',TRANSLATIONS_DIR.'/app.zh_CN.xlf', 'zh_CN', 'app');
        $twig = new \Twig_Environment(new \Twig_Loader_Filesystem(array(
            VIEWS_DIR,
            VENDOR_TWIG_BRIDGE_DIR . '/Resources/views/Form',
        )));
        $formEngine = new TwigRendererEngine();
        $formEngine->setEnvironment($twig);

        $twig->addExtension(new TranslationExtension($translator));
        $twig->addExtension(
            new FormExtension(new TwigRenderer($formEngine,$csrfTokenManager))
        );
        $formFactory = Forms::createFormFactoryBuilder()
            ->addExtension(new CsrfExtension($csrfTokenManager))
            ->addExtension(new ValidatorExtension($validator))
            ->getFormFactory();
        $container->set('form.factory',$formFactory);
    }
}
